package com.springboot.ww.config;

import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.springboot.ww.config.dynamic.TenantDynamicDataSourceProvider;
import com.springboot.ww.config.dynamic.TenantDynamicRoutingDataSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Random;

/**
 *
 *
 * 日志：SqlLogInterceptor
 *
 * @author panyun
 * @date 2020/11/3 16:45
 */
@Configuration
@MapperScan(basePackages = {"com.springboot.ww.mapper"}, sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DbConfig {

    private Random random = new Random();

    @Bean(name = "test1DataSource")
    @Primary
    public DataSource getDateSource1(@Qualifier("tenantDynamicDataSourceProvider") DynamicDataSourceProvider dynamicDataSourceProvider) {
        TenantDynamicRoutingDataSource tenantDynamicRoutingDataSource = new TenantDynamicRoutingDataSource();
        tenantDynamicRoutingDataSource.setProvider((TenantDynamicDataSourceProvider) dynamicDataSourceProvider);
        return tenantDynamicRoutingDataSource;
    }

    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource,
                                                    ObjectProvider<Interceptor[]> interceptorsProvider) throws Exception {
        // mybatis-puls要使用 MybatisSqlSessionFactoryBean
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setPlugins(interceptorsProvider.getIfAvailable());
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/springboot/ww/mapper/*.xml"));
        GlobalConfig config = new GlobalConfig().setBanner(false);
        config.setWorkerId(Long.valueOf(random.nextInt(30) + 1));
        config.setDatacenterId(Long.valueOf(random.nextInt(30) + 1));
        bean.setGlobalConfig(config);
        return bean.getObject();
    }

    @Bean("test1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate test1sqlsessiontemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}
